var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

/**
 * Created by Small on 2017/4/2.
 * Version 2.0
 */
window.Pager = function () {
	var _Table = function () {
		//obj url tpl page
		function _Table(param) {
			_classCallCheck(this, _Table);

			this.param = {};
			this.staticParam = {};
			this.size = 0;
			this.offset = -1;
			this._data = null;
			this.fun = null;
			for (var x in param) {
				if (x in _Table.staticKeys) {
					this.staticParam[x] = param[x];
				} else this[x] = param[x];
			}
		}

		_createClass(_Table, [{
			key: 'loadPage',
			value: function loadPage(page) {
				this.offset = parseInt(page);
				this.param.offset = page;
				ajaxObj(this.url, 'post', this.param, function(d){
					this.showData(d);
				}.bind(this));
				/*$.post(this.url, this.param, function (d) {
					this.showData(d);
				}.bind(this), 'json');*/
			}
		}, {
			key: 'showData',
			value: function showData(d) {
				var reg = /{\w+?}/g,
				    res = '',
				    data,
				    count = 0;
				if (typeof d.total == 'undefined') {
					data = d;
					this.total = 1;
					count = data.length;
				} else {
					data = d.data;
					count = d.total;
					if (count == 0) {
						layer.msg("暂无数据!", { time: 1000 });
					}
					this.size = Math.max(this.size, data.length);
					this.total = Math.ceil(count / this.size);
				}
				var pageStr = Pager.pager.draw(this.offset + 1, this.total, this.index);
				this.foot.find('.pager-page').html(pageStr);
				this.foot.find('.pager-total').html(count);
				if (typeof this.fun == 'function') data = this.fun(data);
				this._data = data;
				data.map(function (v, index) {
					res += this.tpl.replace(reg, function (word) {
						var key = word.substr(1, word.length - 2);
						return v[key];
					});
				}.bind(this));
				this.target.html(res);
			}
		}, {
			key: 'reload',
			value: function reload(reset) {
				if (reset) {
					this.offset == 0 ? this.loadPage(0) : Pager.jump(0, this.index); //page is not 0,so we need to change the hash
				} else {
					this.loadPage(this.offset);
				}
			}
		}, {
			key: 'getRow',
			value: function getRow(key, value) {
				var _iteratorNormalCompletion = true;
				var _didIteratorError = false;
				var _iteratorError = undefined;

				try {
					for (var _iterator = this._data[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
						var v = _step.value;

						if (v[key] == value) return v;
					}
				} catch (err) {
					_didIteratorError = true;
					_iteratorError = err;
				} finally {
					try {
						if (!_iteratorNormalCompletion && _iterator.return) {
							_iterator.return();
						}
					} finally {
						if (_didIteratorError) {
							throw _iteratorError;
						}
					}
				}

				return null;
			}
		}, {
			key: 'addParam',
			value: function addParam(key, value) {
				this.param[key] = value;
			}
		}, {
			key: 'delParam',
			value: function delParam(key) {
				delete this.param[key];
			}
		}]);

		return _Table;
	}();

	_Table.staticKeys = ['size', 'sort', 'sortType'];
	$(window).bind('hashchange', function () {
		Pager.dispatch();
	});
	return {
		instance: [],
		link: {},
		init: function init(fun) {
			var t;
			var keys = ['url', 'tpl', 'foot', 'size', 'sort', 'sortType'];
			var self = this;
			$('.pager-table').each(function () {
				var obj = $(this);
				var param = { obj: obj, target: obj.find('tbody') };
				var _iteratorNormalCompletion2 = true;
				var _didIteratorError2 = false;
				var _iteratorError2 = undefined;

				try {
					for (var _iterator2 = keys[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
						var key = _step2.value;

						if (t = obj.data(key)) param[key] = t;
					}
				} catch (err) {
					_didIteratorError2 = true;
					_iteratorError2 = err;
				} finally {
					try {
						if (!_iteratorNormalCompletion2 && _iterator2.return) {
							_iterator2.return();
						}
					} finally {
						if (_didIteratorError2) {
							throw _iteratorError2;
						}
					}
				}

				if (!('url' in param)) param['url'] = location.pathname;
				if ('tpl' in param) param['tpl'] = $('#' + param['tpl']).html();else param['tpl'] = $('#item').html();
				if ('foot' in param) param['foot'] = $('#' + param['foot']);else param['foot'] = obj.parent().find('.pager-foot');
				var sort = '';
				var sortType = '';
				if ('sort' in param) {
					sort = param['sort'];
					if ('sortType' in param) sortType = param['sortType'];else {
						sortType = 'asc';
						param['sortType'] = 'asc';
					}
				}

				var index = self.instance.push(new _Table(param)) - 1;
				if (t = obj.attr('id')) self.link[t] = self.instance[index];
				self.instance[index].index = index;

				//设置默认排序
				obj.find('.pager-sort').each(function () {
					var th = $(this);
					if (th.data('sort') == sort) {
						th.addClass('pager-sort-' + sortType);
					}
				});
				//添加绑定事件
				obj.on('click', '.pager-sort', function () {
					var th = $(this);
					var ins = self.instance[index];
					if (th.hasClass('pager-sort-asc')) {
						ins.staticParam['sortType'] = 'desc';
						th.removeClass('pager-sort-asc').addClass('pager-sort-desc');
					} else if (th.hasClass('pager-sort-desc')) {
						ins.staticParam['sortType'] = 'asc';
						th.removeClass('pager-sort-desc').addClass('pager-sort-asc');
					} else {
						obj.find('.pager-sort-asc').removeClass('pager-sort-asc');
						obj.find('.pager-sort-desc').removeClass('pager-sort-desc');
						ins.staticParam['sortType'] = 'asc';
						ins.staticParam['sort'] = th.data('sort');
						th.addClass('pager-sort-asc');
					}
					ins.reload(true);
				});
			});
			typeof fun == 'function' && fun();
			this.dispatch();
		},
		jump: function jump(page) {
			var index = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;

			if (isNaN(index)) {
				index = index in this.link ? this.link[index].index : 0;
			}
			var hash = [];
			var _iteratorNormalCompletion3 = true;
			var _didIteratorError3 = false;
			var _iteratorError3 = undefined;

			try {
				for (var _iterator3 = this.instance[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
					var o = _step3.value;

					hash.push(o.param);
				}
			} catch (err) {
				_didIteratorError3 = true;
				_iteratorError3 = err;
			} finally {
				try {
					if (!_iteratorNormalCompletion3 && _iterator3.return) {
						_iterator3.return();
					}
				} finally {
					if (_didIteratorError3) {
						throw _iteratorError3;
					}
				}
			}

			hash[index].offset = page;
			location.href = '#' + hash.map(function (v) {
				return $.param(v);
			}).join('|');
		},
		getObj: function getObj(id) {
			if (id in this.link) return this.link[id];else return null;
		},
		dispatch: function dispatch() {
			var hash = location.hash.substr(1);
			var param = [];
			hash != '' && hash.split('|').map(function (table) {
				var item = { offset: 0 };
				table != '' && table.split('&').map(function (v) {
					var kv = v.split('=');
					item[kv[0]] = kv[1];
				});
				param.push(item);
			});
			for (var index in this.instance) {
				var element = this.instance[index];
				var page = index in param ? param[index].offset : 0;
				if (element.offset != page) {
					element.loadPage(page);
				}
			}
		},
		next: function next() {
			var index = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;

			var obj = isNaN(index) ? this.getObj(index) : this.instance[index];
			var page = obj.offset;
			if (typeof obj.total != 'undefined' && obj.total <= page + 1) return;
			this.jump(page + 1, obj.index);
		},
		pre: function pre() {
			var index = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;

			var obj = isNaN(index) ? this.getObj(index) : this.instance[index];
			var page = obj.offset;
			if (page == 0) return;
			this.jump(page - 1, obj.index);
		},
		reload: function reload() {
			var reset = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
			var index = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;

			var obj = isNaN(index) ? this.getObj(index) : this.instance[index];
			obj.reload(reset);
		},
		pager: {
			tpl: {
				omi: '<li class="paginate_button"><a>……</a></li>',
				jump: '<li class="paginate_button"><a href="{href}">{page}</a></li>',
				active: '<li class="paginate_button active"><a href="javascript:;">{page}</a></li>',
				before: '',
				after: ''
			},
			draw: function draw(num, total, index) {
				this.index = index;
				if (isNaN(num) || total < num) {
					num = 1;
				}
				var res = '',
				    a = 1;
				if (total <= 5) {
					for (a = 1; a <= total; a++) {
						if (a == num) res += this.here(num);else res += this.jump(a);
					}
				} else if (num >= 3) {
					res += this.jump(1) + this.tpl.omi;
					res += this.jump(num - 1);
					res += this.here(num);
					if (num < total) {
						res += this.jump(num + 1);
						if (total - num > 2) res += this.tpl.omi + this.jump(total);else if (total - num == 2) res += this.jump(total);
					}
				} else {
					for (a = 1; a <= 3; a++) {
						if (a == num) res += this.here(num);else res += this.jump(a);
					}
					res += this.tpl.omi + this.jump(total);
				}
				return this.tpl.before.replace(/{index}/g, index) + res + this.tpl.after.replace(/{index}/g, index);
			},
			jump: function jump(page) {
				return this.tpl.jump.replace('{page}', page).replace('{href}', 'javascript:Pager.jump(' + (page - 1) + ',' + this.index + ')');
			},
			here: function here(page) {
				return this.tpl.active.replace('{page}', page);
			}
		}
	};
}();
